/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[CharacterEncodingFilter.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package filter.cases;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import filter.HttpFilter;

/**
 * 字符编码过滤器
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebFilter(filterName = "CharacterEncodingFilter", urlPatterns = "/*")
public class CharacterEncodingFilter extends HttpFilter {

	private String characterEncoding;

	@Override
	public void init() {
		characterEncoding = this.getFilterConfig().getServletContext().getInitParameter("characterEncoding");
	}

	@Override
	public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		if (characterEncoding == null || "".equals(characterEncoding)) {
			characterEncoding = "UTF-8";
		}
		request.setCharacterEncoding(characterEncoding);
		response.setCharacterEncoding(characterEncoding);
		response.setContentType("text/html;charset=" + characterEncoding);

		CharacterEncodingRequest requestWrapper = new CharacterEncodingRequest(request);

		filterChain.doFilter(requestWrapper, response);
	}
}

/**
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 *
 */
class CharacterEncodingRequest extends HttpServletRequestWrapper {

	// 定义一个变量记住被增强对象[request对象是需要被增强的对象]
	private HttpServletRequest request;

	public CharacterEncodingRequest(HttpServletRequest request) {
		super(request);
		this.request = request;
	}

	@Override
	public String getParameter(String name) {
		try {
			String value = this.request.getParameter(name);
			if (value == null) {
				return "";
			}

			// 为get方法得到的请求参数编码
			if ("get".equalsIgnoreCase(this.request.getMethod())) {
				value = new String(value.getBytes("UTF-8"), this.request.getCharacterEncoding());
				return value;
			} else {
				// 不是get方法提交的数据直接返回
				return value;
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
